<template>
  <div class="app-container">
    <el-row :gutter="20" class="mb8">
      <el-col>
        <div v-text="queryParams.portName+' 报错规则'" style="color: #5a5e66; font-weight：100;"></div>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pm:excPortUpdateCondition:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['pm:excPortUpdateCondition:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:excPortUpdateCondition:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['pm:excPortUpdateCondition:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="excPortUpdateConditionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--      <el-table-column label="${comment}" align="center" prop="id"/>-->
      <el-table-column label="比较字段" align="center" prop="outFieldFormula"/>
      <el-table-column label="匹配类型" align="center">
        <template slot-scope="scope">
          {{ getMatchTypeName(scope.row.matchingType) }}
        </template>
      </el-table-column>

      <el-table-column label="比较值" align="center" prop="matchingValue"/>
      <el-table-column label="比较类型" align="center" prop="compareFlag"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:excPortUpdateCondition:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:excPortUpdateCondition:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改请求返回订单修改限制条件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>

      <div class="addBox">
        <div class="form">
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">

            <el-form-item label="比较字段" prop="outFieldFormula">
              <el-input v-model="form.outFieldFormula" placeholder="请输入比较字段"/>
            </el-form-item>

            <el-form-item label="匹配类型" prop="matchingType">
              <el-select v-model="form.matchingType" placeholder="请选择匹配类型">
                <el-option
                  v-for="item in matchingTypeList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="比较值" prop="matchingValue" v-if="form.matchingType == 2">
              <el-input v-model="form.matchingValue" placeholder="请输入比较值"/>
            </el-form-item>

            <el-form-item label="比较值" prop="matchingValue" v-if="form.matchingType == 1">

              <el-input placeholder="请输入正则表达式" v-model="form.matchingValue" class="input-with-select">
                <template slot="prepend">/</template>
                <template slot="append">{{ matchValueRegSuffix }}</template>
              </el-input>

            </el-form-item>

            <el-form-item label="" prop="" v-if="form.matchingType == 1">
              <el-checkbox-group v-model="selectRegSuffix" size="mini">
                <el-checkbox-button v-for="suffix in regSuffixList" :label="suffix.value" :value="suffix.value"
                                    :key="suffix.value"
                >{{ suffix.name }}
                </el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="比较类型" prop="compareFlag" v-if="form.matchingType == 2">
              <el-select v-model="form.compareFlag" placeholder="请选择比较类型">
                <el-option
                  v-for="item in compareFlagList"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="验证正则" prop="compareFlag" v-if="form.matchingType == 1">
              <el-input type="textarea" v-model="testRegularForm"></el-input>
              <p>输入数据，点击验证按钮，验证正则表达式是否正确</p>
              <div>
                <el-button type="primary" plain @click="handleTestReuglar">
                  验证正则
                </el-button>
              </div>
            </el-form-item>

          </el-form>
        </div>

        <div class="tree">
          <div class="head-container">
            <el-input
              v-model="fieldName"
              placeholder="请输入字段名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree :data="treeData"
                     default-expand-all
                     :filter-node-method="filterNode"
                     ref="tree"
                     :props="defaultProps"
                     @node-click="handleNodeClick"
                     :expand-on-click-node="false"
                     :highlight-current="true"
            ></el-tree>
          </div>
        </div>
      </div>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listExcPortUpdateCondition,
  getExcPortUpdateCondition,
  delExcPortUpdateCondition,
  addExcPortUpdateCondition,
  updateExcPortUpdateCondition
} from "@/api/pm/excPortUpdateCondition";
import {listExcPortConfig} from "@/api/pm/excPortConfig";
import {list2FieldTree} from "@/views/pm/excPortConfig/js/common";

export default {
  name: "ExcPortUpdateCondition",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请求返回订单修改限制条件表格数据
      excPortUpdateConditionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        portId: this.$route.query.portId,
        portName: this.$route.query.portName,
        outFieldFormula: null,
        matchingType: null,
        matchingValue: null,
        compareFlag: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        portId: [
          {required: true, message: "接口id不能为空", trigger: "blur"}
        ],
        outFieldFormula: [
          {required: true, message: "比较字段公式不能为空", trigger: "change"}
        ],
        matchingType: [
          {required: true, message: "请选择比较类型", trigger: "change"}
        ],
        matchingValue: [
          {required: true, message: "比较值不能为空", trigger: "blur"}
        ],
      },

      // 匹配类型1：正则，2:比较
      matchingTypeList: [
        {name: '正则', value: '1'},
        {name: '比较', value: '2'}
      ],

      // 比较类型
      compareFlagList: [
        {name: ">="},
        {name: "="},
        {name: "<="},
        {name: "<>"},
        {name: "in"},
        {name: "not-in"},
      ],

      treeData: [],
      fieldName: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      // 正则表单式要验证的值
      testRegularForm: '',
      selectRegSuffix: [],
      regSuffixList: [
        {name: '全局搜索 -g', value: 'g'},
        {name: '忽略大小写 -i', value: 'i'},
        {name: '多行模式 -m', value: 'm'},
        {name: '包含换行符 -s', value: 's'}
      ],
      matchValueRegSuffix: "/"
    };
  },
  computed: {
    getMatchTypeName() {
      return function (value) {
        let obj = this.matchingTypeList.find(item => item.value == value);
        return obj?.name;
      }
    }
  },
  watch: {
    fieldName(val) {
      this.$refs['tree'].filter(val);
    },
    selectRegSuffix(val) {
      let suffix = '/';
      for(let item of val) {
        suffix += item;
      }

      this.matchValueRegSuffix = suffix;
    }
  },
  created() {
    this.getList();

    let portId = this.$route.query.portId || '';
    this.getTreeData(portId);
  },
  methods: {
    /** 查询请求返回订单修改限制条件列表 */
    getList() {
      this.loading = true;
      listExcPortUpdateCondition(this.queryParams).then(response => {
        this.excPortUpdateConditionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /**
     * 获取比较字段列表
     * @param portId 接口id
     */
    getTreeData(portId) {
      if(!portId) return;

      let params = {
        type: 2,
        pageNum: 1,
        pageSize: 1000,
        portId: portId
      };

      listExcPortConfig(params).then(res => {
        let data = res.code == 200 ? res.rows : [];

        this.treeData = list2FieldTree(data);
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        portId: this.$route.query.portId,
        outFieldFormula: null,
        matchingType: null,
        matchingValue: null,
        compareFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加请求返回订单修改限制条件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeData();
      const id = row.id || this.ids
      getExcPortUpdateCondition(id).then(response => {
        this.form = response.data;

        let type = this.form.matchingType;
        if(type == 1) { //正则类型的处理比较值
          this.form.matchingValue = this.dealMatchingValue(this.form.matchingValue);
        }

        this.open = true;
        this.title = "修改请求返回订单修改限制条件";
      });
    },

    dealMatchingValue(str) {
      let firstKey = str.indexOf('/');
      let lastKey  = str.lastIndexOf('/');

      let word = str.substring(firstKey+1, lastKey);

      let lastWord  = str.substring(lastKey+1, str.length);
      let lastWordArr = lastWord.split("");
      this.selectRegSuffix = lastWordArr;

      return word;
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {

            let type   = this.form.matchingType;
            let params = JSON.parse(JSON.stringify(this.form));
            if(type == 1) { //正则
              params.matchingValue = `/${this.form.matchingValue}${this.matchValueRegSuffix}`;
            }

            updateExcPortUpdateCondition(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let type   = this.form.matchingType;
            let params = JSON.parse(JSON.stringify(this.form));
            if(type == 1) { //正则
              params.matchingValue = `/${this.form.matchingValue}${this.matchValueRegSuffix}`;
            }

            addExcPortUpdateCondition(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        return delExcPortUpdateCondition(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pm/excPortUpdateCondition/export', {
        ...this.queryParams
      }, `excPortUpdateCondition_${new Date().getTime()}.xlsx`)
    },

    // 过滤节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    //树型结构方法
    handleNodeClick(data) {
      console.log('点击的数据为', data);

      let path = data?.path;
      this.form.outFieldFormula = path;
      this.form.portConfigId = data?.id;
    },

    // 验证正则表达式
    handleTestReuglar() {
      if (!this.testRegularForm) {
        this.$message.error('请输入要验证的正则数据');
        return;
      }

      let regStr = this.form.matchingValue;
      let patternType = this.selectRegSuffix.join('');

      // 将字符串转为正则表达式
      let reg = new RegExp(regStr, patternType);

      if (!reg.test(this.testRegularForm)) {
        this.$message.error('验证失败，请检查正则表达式是否编写正确');
        return;
      } else {
        this.$message.success('验证成功');
      }
    }

  }
};
</script>

<style scoped>
.addBox {
  display: flex;
  justify-content: space-around;
}

.form {
  width: 550px;
}

.tree {
  width: 380px;
}

</style>
